package com.example.lenovo.asia5b.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.lenovo.asia5b.home.bean.UserBean;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.JsonTools2;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.SMSCode;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;

/**
 * Created by lenovo on 2017/6/28.
 */

public class ForgotPasswordActivity extends BaseActivity implements ICallBack {
    private LoadingDalog loadingDalog;

    private TimeCount timeCount;
    private long timeOut;

    private EditText activity_forgot_password_phone,activity_forgot_password_code,
            activity_forgot_password_new,activity_forgot_password_countersign;
    private Button activity_forgot_password_msm;

    private String phone;
    private String from;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgot_password);
        initView();
    }

    public void initView() {
        Intent intent = getIntent();
        from = intent.getStringExtra("from");

        loadingDalog = new LoadingDalog(this);
        activity_forgot_password_msm = findViewById(R.id.activity_forgot_password_msm);//获取验证码
        activity_forgot_password_phone = findViewById(R.id.activity_forgot_password_phone);//手机
        activity_forgot_password_new = findViewById(R.id.activity_forgot_password_new);//新密码
        activity_forgot_password_countersign = findViewById(R.id.activity_forgot_password_countersign);//确认新密码
        activity_forgot_password_code = findViewById(R.id.activity_forgot_password_code);//验证码

        F.id(R.id.public_title_name).text(getResources().getString(R.string.forgot_password));
        if(TextUtils.equals("loginpassword",from)){
            F.id(R.id.activity_forgot_password_title).text(getString(R.string.retrieve_the_password));
        }else if(TextUtils.equals("paypassword",from)){
            F.id(R.id.activity_forgot_password_title).text(getString(R.string.pay_back_the_password));
            F.id(R.id.activity_forgot_password_phone).text(getUserBean().mobile_phone);
            F.id(R.id.ll_forgot_password_phone).visibility(View.GONE);
        }
        F.id(R.id.public_btn_left).clicked(this);
        F.id(R.id.activity_forgot_password_msm).clicked(this);
        F.id(R.id.activity_forgot_password_next).clicked(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.public_btn_left:
                finish();
                break;
            case R.id.activity_forgot_password_msm:
                phone = activity_forgot_password_phone.getText().toString();
                loadingDalog.show();
                SMSCode.getCode(this,phone);
                break;
            case R.id.activity_forgot_password_next://完成
                String code = activity_forgot_password_code.getText().toString();//验证码
                if(!TextUtils.isEmpty(code)){
                    if(timeOut <= 1){
                        U.Toast(this,getResources().getString(R.string.yzmsx));
                    }else{
                        if(TextUtils.equals("loginpassword",from)){
                            backLoginPassword(code);//忘记登录密码
                        }else if(TextUtils.equals("paypassword",from)){
                            backPayPassword(code);//忘记支付密码
                        }
                    }
                }else{
                    U.Toast(this,getResources().getString(R.string.yzmbnwk));
                }
                break;
            default:
                break;
        }
    }

    /**
     * 取回登录密码
     * @param code
     */
    private void backLoginPassword(String code){
        try{
            String new_pass = activity_forgot_password_new.getText().toString().trim();
            String countersignNewpwd = activity_forgot_password_countersign.getText().toString().trim();
            phone = activity_forgot_password_phone.getText().toString().trim();
            if(!TextUtils.isEmpty(phone)){
                if(!TextUtils.isEmpty(new_pass)){
                    if(new_pass.length() >= 6){
                        if(!TextUtils.isEmpty(countersignNewpwd)){
                            if(TextUtils.equals(new_pass,countersignNewpwd)){
                                loadingDalog.show();
                                String setPWDURL = Setting.BACKPASS;
                                Map<String,String> map = new HashMap<String,String>();
                                map.put("phone",phone);
                                map.put("new_pass",new_pass);
                                map.put("code",code);
                                Date date = new Date();
                                String time = String.valueOf(date.getTime());
                                map.put("time",time);
                                String[] storStr = {"phone"+phone,"new_pass"+new_pass,"code"+code,"time"+time};
                                String stor = Logic.sortToString(storStr);
                                String md5 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(stor));
                                map.put("sign",md5);

                                JsonTools.getJsonAll(this,setPWDURL,map,1);
                                JsonTools2.setOne(true);
                            }else{
                                U.Toast(this,getResources().getString(R.string.lcsrdmmbxd));
                            }
                        }else{
                            U.Toast(this,getResources().getString(R.string.qrxmmbnwk));
                        }
                    }else{
                        U.Toast(this,getResources().getString(R.string.xmmcdbxdy6));
                    }
                }else{
                    U.Toast(this,getResources().getString(R.string.xmmbnwk));
                }
            }else{
                U.Toast(this,getResources().getString(R.string.sjhbnwk));
            }
        }catch (Exception e){
//            Log.e("忘记密码error：",e.getMessage());
        }
    }

    /**
     * 取回支付密码
     * @param code
     */
    private void backPayPassword(String code){
        try{
            String new_pass = activity_forgot_password_new.getText().toString().trim();
            String countersignNewpwd = activity_forgot_password_countersign.getText().toString().trim();
            phone = activity_forgot_password_phone.getText().toString().trim();
            if(!TextUtils.isEmpty(phone)){
                if(!TextUtils.isEmpty(new_pass)){
                    if(new_pass.length() == 6){
                        if(!TextUtils.isEmpty(countersignNewpwd)){
                            if(TextUtils.equals(new_pass,countersignNewpwd)){
                                loadingDalog.show();
                                String setPWDURL = Setting.BACKPAYPASS;
                                Map<String,String> map = new HashMap<String,String>();
                                map.put("phone",phone);
                                UserBean user = (UserBean)SharedPreferencesUtils.getObjectFromShare("user");
                                map.put("user_id",user.user_id);
                                map.put("new_paypass",new_pass);
                                map.put("code",code);
                                Date date = new Date();
                                String time = String.valueOf(date.getTime());
                                map.put("time",time);
                                String[] storStr = {"user_id"+user.user_id,"phone"+phone,"new_paypass"+new_pass,"code"+code,"time"+time};
                                String stor = Logic.sortToString(storStr);
                                String md5 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(stor));
                                map.put("sign",md5);

                                JsonTools.getJsonAll(this,setPWDURL,map,2);
                                JsonTools2.setOne(true);
                            }else{
                                U.Toast(this,getResources().getString(R.string.lcsrdmmbxd));
                            }
                        }else{
                            U.Toast(this,getResources().getString(R.string.qrxmmbnwk));
                        }
                    }else{
                        U.Toast(this,getResources().getString(R.string.xmmcdbxdy6));
                    }
                }else{
                    U.Toast(this,getResources().getString(R.string.qrxmmbnwk));
                }
            }else{
                U.Toast(this,getResources().getString(R.string.sjhbnwk));
            }
        }catch (Exception e){
//            Log.e("忘记密码error：",e.getMessage());
        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;

            Intent intent = null;
            try{
                if(result != null){
                    JSONObject jsonObject = (JSONObject)result;
                    if(action == 0){
                        String msgText = jsonObject.getString("MsgText");
                        if("true".equals(msgText)){
                            timeCount = new TimeCount(60000, 1000);
                            timeCount.start();
                            String state = jsonObject.getString("State");
                            U.Toast(ForgotPasswordActivity.this,state);
                        }else if("false".equals(msgText)){
                            String state = jsonObject.getString("State");
                            U.Toast(ForgotPasswordActivity.this,state);
                        }
                        loadingDalog.dismiss();
                    }else if(action == 1){
                        int state = jsonObject.getInt("State");
                        if(state == 0){
                            intent = new Intent(ForgotPasswordActivity.this,LoginActivity.class);
                            loadingDalog.dismiss();
                            U.Toast(ForgotPasswordActivity.this,getResources().getString(R.string.mmczcg));
                            startActivityForResult(intent,300);
                        }else if(state == 1){
                            loadingDalog.dismiss();
                            U.Toast(ForgotPasswordActivity.this,getResources().getString(R.string.qmsb));
                        }else if(state == 2){
                            loadingDalog.dismiss();
                            U.Toast(ForgotPasswordActivity.this,getResources().getString(R.string.cscw));
                        }else if(state == 3){
                            loadingDalog.dismiss();
                            U.Toast(ForgotPasswordActivity.this,getResources().getString(R.string.wdl));
                        }else if(state == 4){
                            loadingDalog.dismiss();
                            U.Toast(ForgotPasswordActivity.this,getResources().getString(R.string.sjyzmcw));
                        }else if(state == 5){
                            loadingDalog.dismiss();
                            U.Toast(ForgotPasswordActivity.this,getResources().getString(R.string.modify_defeated));
                        }else if(state == 15){
                            U.Toast(ForgotPasswordActivity.this,getResources().getString(R.string.yzmsx));
                        }
                    }else if(action == 2){
                        int state = jsonObject.getInt("State");
                        if(state == 0){
                            U.Toast(ForgotPasswordActivity.this,getResources().getString(R.string.mmczcg));
                            finish();
                        }else if(state == 1){
                            U.Toast(ForgotPasswordActivity.this,getResources().getString(R.string.qmsb));
                        }else if(state == 2){
                            U.Toast(ForgotPasswordActivity.this,getResources().getString(R.string.cscw));
                        }else if(state == 3){
                            U.Toast(ForgotPasswordActivity.this,getResources().getString(R.string.sjyzmcw));
                        }else if(state == 4){
                            U.Toast(ForgotPasswordActivity.this,getResources().getString(R.string.wdl));
                        }else if(state == 5){
                            U.Toast(ForgotPasswordActivity.this,getResources().getString(R.string.clyc));
                        }else if(state == 15){
                            U.Toast(ForgotPasswordActivity.this,getResources().getString(R.string.yzmsx));
                        }
                    }
                }else{
//                U.Toast(this,"连接服务器失败："+result);
                }
            }catch (Exception e){
                Log.e("忘记密码JSONerror:",e.getMessage());
            }
            loadingDalog.dismiss();
        }
    };


    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    /**
     * 获取验证码倒计时
     */
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if(ForgotPasswordActivity.this.isFinishing()){
                return;
            }
            activity_forgot_password_msm.setClickable(false);
            timeOut = millisUntilFinished / 1000;
            activity_forgot_password_msm.setText(getResources().getString(R.string.message_has_been_sent)+"(" + timeOut + ")");
        }

        @Override
        public void onFinish() {
            activity_forgot_password_msm.setText(getResources().getString(R.string.to_obtain_the_verification_code));
            activity_forgot_password_msm.setClickable(true);
        }
    }
}
